package com.hu.network.http.request;

import java.io.File;

import com.hu.network.http.bodyImpl.RequestBodyImpl;
import com.hu.network.http.other.MimeType;
import com.hu.network.http.request.method.PostMethod;
import com.hu.network.util.JsonHelper;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 说明：
 *
 * @author ： hucanhua
 * @date ： 2017/10/26
 */
public abstract class BasePostHttpRequest<T> extends BaseHttpRequest<T> {
    public BasePostHttpRequest(ProgressCallback requestCallback, ProgressCallback responseCallback) {
        super(requestCallback, responseCallback);
    }

    protected abstract RequestBody getParams();

    @Override
    protected final Request getRequest() {
        return new PostMethod(getTag(), getUrl(), new RequestBodyImpl(getParams(), new RequestBodyImpl.ProgressListener() {
            @Override
            public void progress(long bytesRead, long contentLength, boolean done) {
                if (requestCallback != null) {
                    requestCallback.progress(bytesRead, contentLength, done);
                }
            }
        })).getRequest();
    }

    protected final RequestBody getRequestBody(Object value, MimeType mimeType) {
        RequestBody body = null;
        switch (mimeType) {
            case FILE:
                body = RequestBody.create(mimeType.getMediaType(), (File) value);
                break;
            case JSON:
                body = RequestBody.create(mimeType.getMediaType(), JsonHelper.toJsonString(value));
                break;
            case TEXT:
                body = RequestBody.create(mimeType.getMediaType(), (String) value);
                break;
            case IMAGE:
                body = RequestBody.create(mimeType.getMediaType(), (File) value);
                break;
            default:
                break;
        }
        return body;
    }
}
